import React, { useState, Suspense } from 'react';
import { MenuFoldOutlined, MenuUnfoldOutlined } from '@ant-design/icons';
import { Button, Layout, Menu, theme, Spin } from 'antd';

const { Header, Sider, Content } = Layout;
import { routes } from './routes';

const App: React.FC = () => {
  const [collapsed, setCollapsed] = useState(false);
  const [current, setCurrent] = useState(routes[0]);
  const [CurrentComponent, setCurrentComponent] =
    useState<React.ComponentType | null>(null);
  const {
    token: { colorBgContainer, borderRadiusLG },
  } = theme.useToken();

  // 懒加载组件
  const loadComponent = async (
    componentImport: () => Promise<{ default: React.ComponentType }>
  ) => {
    try {
      const module = await componentImport();
      const Component = module.default || module;
      setCurrentComponent(() => Component);
    } catch (error) {
      console.error('Failed to load component:', error);
    }
  };

  // 初始化加载第一个组件
  React.useEffect(() => {
    if (current?.component) {
      loadComponent(current.component);
    }
  }, [current]);

  const handlePopState = () => {
    const currentPath = window.location.pathname;
    const matchingRoute = routes.find(route => route.path === currentPath);
    if (matchingRoute) {
      setCurrent(matchingRoute);
    }
  };

  // 处理浏览器前进/后退按钮和初始化路由
  React.useEffect(() => {
    // 初始化时根据当前 URL 设置路由
    handlePopState();
    // 添加事件监听器
    window.addEventListener('popstate', handlePopState);
    return () => window.removeEventListener('popstate', handlePopState);
  }, []);

  const items = routes.map(route => ({
    key: route.name,
    icon: route.icon,
    label: route.name,
    path: route.path,
    component: route.component,
  }));

  const handleMenuClick = ({ key }: { key: string }) => {
    const selectedRoute = routes.find(route => route.name === key);
    if (selectedRoute) {
      setCurrent(selectedRoute);
      // 更新 URL 但不刷新页面
      window.history.pushState(null, '', selectedRoute.path);
    }
  };

  return (
    <Layout style={{ height: '100vh' }}>
      <Sider trigger={null} collapsible collapsed={collapsed}>
        <div className="demo-logo-vertical" />
        <Menu
          theme="dark"
          mode="inline"
          defaultSelectedKeys={[current.name]}
          selectedKeys={[current.name]}
          items={items}
          onClick={handleMenuClick}
        />
      </Sider>
      <Layout>
        <Header style={{ padding: 0, background: colorBgContainer }}>
          <Button
            type="text"
            icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
            onClick={() => setCollapsed(!collapsed)}
            style={{
              fontSize: '16px',
              width: 64,
              height: 64,
            }}
          />
        </Header>
        <Content
          style={{
            margin: '24px 16px',
            padding: 24,
            minHeight: 280,
            background: colorBgContainer,
            borderRadius: borderRadiusLG,
          }}
        >
          <Suspense
            fallback={
              <Spin
                size="large"
                style={{
                  display: 'flex',
                  justifyContent: 'center',
                  alignItems: 'center',
                  height: '200px',
                }}
              />
            }
          >
            {CurrentComponent ? <CurrentComponent /> : null}
          </Suspense>
        </Content>
      </Layout>
    </Layout>
  );
};

export default App;
